<template>
  <div class="absolute inset-0 overflow-hidden pointer-events-none">
    <div class="relative h-full">
      <!-- 动态弹幕容器 -->
      <div ref="barrageContainer" class="absolute inset-0 w-full h-full">
        <!-- 弹幕将通过JavaScript动态生成 -->
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'

interface BarrageItem {
  type: 'stats' | 'tag'
  text: string
  value?: string
  color?: string
  tag?: string
}

interface Props {
  statsData?: {
    total?: number
    solved?: number
    rate?: number
    submissions?: number
  }
  customBarrageData?: BarrageItem[]
}

const props = withDefaults(defineProps<Props>(), {
  statsData: () => ({
    total: 0,
    solved: 0,
    rate: 0,
    submissions: 0
  }),
  customBarrageData: () => []
})

const emit = defineEmits<{
  tagClick: [tag: string]
}>()

// 弹幕系统
const barrageContainer = ref<HTMLElement>()
const barrageInterval = ref<number>()
const activeBarrages = ref<Set<HTMLElement>>(new Set())
const activeTags = ref<Set<string>>(new Set()) // 跟踪当前活跃的标签
const occupiedPositions = ref<Set<number>>(new Set()) // 跟踪已占用的位置

// 默认弹幕数据
const defaultBarrageData: BarrageItem[] = [
  // 统计信息
  { type: 'stats', text: '总题数', value: 'total', color: 'blue' },
  { type: 'stats', text: '已解决', value: 'solved', color: 'green' },
  { type: 'stats', text: '通过率', value: 'rate', color: 'purple' },
  { type: 'stats', text: '今日提交', value: 'submissions', color: 'orange' },
  
  // 算法标签 - 数据结构
  { type: 'tag', text: '数组', tag: 'array' },
  { type: 'tag', text: '链表', tag: 'linked-list' },
  { type: 'tag', text: '栈', tag: 'stack' },
  { type: 'tag', text: '队列', tag: 'queue' },
  { type: 'tag', text: '哈希表', tag: 'hash-table' },
  { type: 'tag', text: '堆', tag: 'heap' },
  { type: 'tag', text: '树', tag: 'tree' },
  { type: 'tag', text: '图', tag: 'graph' },
  { type: 'tag', text: '字典树', tag: 'trie' },
  { type: 'tag', text: '并查集', tag: 'union-find' },
  
  // 算法标签 - 算法类型
  { type: 'tag', text: '动态规划', tag: 'dynamic-programming' },
  { type: 'tag', text: '贪心', tag: 'greedy' },
  { type: 'tag', text: '回溯', tag: 'backtracking' },
  { type: 'tag', text: '递归', tag: 'recursion' },
  { type: 'tag', text: '分治', tag: 'divide-and-conquer' },
  { type: 'tag', text: '排序', tag: 'sorting' },
  { type: 'tag', text: '搜索', tag: 'search' },
  
  // 算法标签 - 遍历方式
  { type: 'tag', text: 'BFS', tag: 'breadth-first-search' },
  { type: 'tag', text: 'DFS', tag: 'depth-first-search' },
  { type: 'tag', text: '前序遍历', tag: 'preorder' },
  { type: 'tag', text: '中序遍历', tag: 'inorder' },
  { type: 'tag', text: '后序遍历', tag: 'postorder' },
  
  // 算法标签 - 技巧
  { type: 'tag', text: '双指针', tag: 'two-pointers' },
  { type: 'tag', text: '滑动窗口', tag: 'sliding-window' },
  { type: 'tag', text: '二分查找', tag: 'binary-search' },
  { type: 'tag', text: '快慢指针', tag: 'fast-slow-pointer' },
  { type: 'tag', text: '前缀和', tag: 'prefix-sum' },
  { type: 'tag', text: '差分数组', tag: 'difference-array' },
  
  // 算法标签 - 其他
  { type: 'tag', text: '字符串', tag: 'string' },
  { type: 'tag', text: '数学', tag: 'math' },
  { type: 'tag', text: '位运算', tag: 'bit-manipulation' },
  { type: 'tag', text: '模拟', tag: 'simulation' },
  { type: 'tag', text: '设计', tag: 'design' },
  
  // 问候语和鼓励语
  { type: 'tag', text: '加油！', tag: 'encourage' },
  { type: 'tag', text: '坚持刷题', tag: 'persist' },
  { type: 'tag', text: '每日一题', tag: 'daily' },
  { type: 'tag', text: '算法之美', tag: 'beauty' },
  { type: 'tag', text: '编程乐趣', tag: 'fun' },
  { type: 'tag', text: '思维训练', tag: 'thinking' },
  { type: 'tag', text: '逻辑思维', tag: 'logic' },
  { type: 'tag', text: '代码艺术', tag: 'art' },
  { type: 'tag', text: '数据结构', tag: 'data-structure' },
  { type: 'tag', text: '算法思维', tag: 'algorithm-thinking' },
  { type: 'tag', text: '编程基础', tag: 'fundamentals' },
  { type: 'tag', text: '技术成长', tag: 'growth' },
  { type: 'tag', text: '学习进步', tag: 'progress' },
  { type: 'tag', text: '代码质量', tag: 'quality' },
  { type: 'tag', text: '性能优化', tag: 'optimization' },
  { type: 'tag', text: '系统设计', tag: 'system-design' },
  { type: 'tag', text: '面试准备', tag: 'interview' },
  { type: 'tag', text: '技术面试', tag: 'tech-interview' },
  { type: 'tag', text: '编程挑战', tag: 'challenge' },
  { type: 'tag', text: '代码实现', tag: 'implementation' }
]

// 获取弹幕数据
const barrageData = computed(() => {
  return props.customBarrageData.length > 0 ? props.customBarrageData : defaultBarrageData
})

// 位置检测辅助函数 - 改进版本
const isPositionOccupied = (top: number) => {
  const barrageHeight = 40
  const minSpacing = 60
  
  for (const occupiedTop of occupiedPositions.value) {
    if (Math.abs(top - occupiedTop) < minSpacing) {
      return true
    }
  }
  return false
}

const markPositionOccupied = (top: number) => {
  occupiedPositions.value.add(top)
}

const unmarkPositionOccupied = (top: number) => {
  occupiedPositions.value.delete(top)
}

// 弹幕系统函数
const createBarrage = () => {
  if (!barrageContainer.value) return
  
  const container = barrageContainer.value
  const containerHeight = container.clientHeight
  const containerWidth = container.clientWidth
  
  if (containerHeight === 0 || containerWidth === 0) return
  
  // 避免重复标签 - 最多尝试10次
  let randomData
  let tagAttempts = 0
  const maxTagAttempts = 10
  
  do {
    randomData = barrageData.value[Math.floor(Math.random() * barrageData.value.length)]
    tagAttempts++
  } while (activeTags.value.has(randomData.text) && tagAttempts < maxTagAttempts)
  
  // 如果尝试10次后仍有重复，则允许重复（避免无限循环）
  if (tagAttempts >= maxTagAttempts) {
    randomData = barrageData.value[Math.floor(Math.random() * barrageData.value.length)]
  }
  
  // 标记标签为活跃
  activeTags.value.add(randomData.text)
  
  // 创建弹幕元素
  const barrage = document.createElement('div')
  barrage.className = 'absolute whitespace-nowrap select-none pointer-events-auto cursor-pointer'
  barrage.style.transition = 'transform 0.3s ease, box-shadow 0.3s ease'
  
  // 避免重叠的位置检测 - 改进版本
  const minTop = 20
  const maxTop = containerHeight - 60
  const barrageHeight = 40 // 降低弹幕高度，与统计卡片一致
  const minSpacing = 60 // 调整最小间距
  
  let top
  let positionAttempts = 0
  const maxPositionAttempts = 30 // 增加尝试次数
  
  do {
    top = Math.random() * (maxTop - minTop) + minTop
    positionAttempts++
  } while (isPositionOccupied(top) && positionAttempts < maxPositionAttempts)
  
  // 如果找不到合适位置，使用随机位置
  if (positionAttempts >= maxPositionAttempts) {
    top = Math.random() * (maxTop - minTop) + minTop
  }
  
  // 标记位置为已占用
  markPositionOccupied(top)
  barrage.style.top = `${top}px`
  
  // 从右侧开始
  barrage.style.right = '-200px'
  
  // 设置内容
  if (randomData.type === 'stats') {
    let value = ''
    switch (randomData.value) {
      case 'total':
        value = props.statsData.total?.toString() || '0'
        break
      case 'solved':
        value = props.statsData.solved?.toString() || '0'
        break
      case 'rate':
        value = `${(props.statsData.rate || 0).toFixed(1)}%`
        break
      case 'submissions':
        value = props.statsData.submissions?.toString() || '0'
        break
    }
    
    barrage.innerHTML = `
      <div class="group bg-white/30 backdrop-blur-sm text-gray-600 rounded-full px-3 py-1.5 hover:bg-white/50 transition-all duration-300 transform hover:scale-105 shadow-sm">
        <span class="font-medium text-sm">${randomData.text}</span>
        <span class="ml-1 font-bold text-sm text-${randomData.color}-500">${value}</span>
      </div>
    `
  } else {
    barrage.innerHTML = `
      <div class="group bg-white/20 backdrop-blur-sm text-gray-500 rounded-full px-3 py-1.5 hover:bg-white/40 transition-all duration-300 transform hover:scale-105 shadow-sm cursor-pointer" data-tag="${randomData.tag}">
        <span class="font-medium text-sm">${randomData.text}</span>
      </div>
    `
    
    // 添加点击事件
    barrage.addEventListener('click', () => {
      if (randomData.tag) {
        emit('tagClick', randomData.tag)
      }
    })
  }
  
  // 添加到容器
  container.appendChild(barrage)
  activeBarrages.value.add(barrage)
  
  // 动画移动 - 简化版本
  const duration = 15000 // 固定15秒，均匀移动
  barrage.style.transition = `right ${duration}ms linear`
  
  // 添加点击事件监听器
  barrage.addEventListener('click', (e) => {
    e.stopPropagation()
    
    // 触发标签点击事件
    if (randomData.tag) {
      emit('tagClick', randomData.tag)
    }
  })
  
  // 移动到左侧
  setTimeout(() => {
    barrage.style.right = `${containerWidth + 200}px`
  }, 50)
  
  // 动画结束后移除
  setTimeout(() => {
    if (barrage.parentNode) {
      barrage.parentNode.removeChild(barrage)
    }
    activeBarrages.value.delete(barrage)
    // 从活跃标签中移除
    activeTags.value.delete(randomData.text)
    // 释放位置
    unmarkPositionOccupied(top)
  }, duration + 200) // 增加一点缓冲时间
}

const startBarrage = () => {
  // 初始创建适量弹幕 - 减少密度
  for (let i = 0; i < 6; i++) {
    setTimeout(() => createBarrage(), i * 800) // 增加间隔到0.8秒
  }
  
  // 单个生成器 - 增加间隔
  barrageInterval.value = setInterval(() => {
    createBarrage()
  }, 3000) // 增加到3秒间隔，减少密度
}

const stopBarrage = () => {
  if (barrageInterval.value) {
    clearInterval(barrageInterval.value)
    barrageInterval.value = undefined
  }
  
  // 清除所有弹幕
  activeBarrages.value.forEach(barrage => {
    if (barrage.parentNode) {
      barrage.parentNode.removeChild(barrage)
    }
  })
  activeBarrages.value.clear()
  // 清除活跃标签
  activeTags.value.clear()
  // 清除占用位置
  occupiedPositions.value.clear()
}

onMounted(async () => {
  await nextTick()
  startBarrage()
})

onUnmounted(() => {
  stopBarrage()
})
</script>
